package com.youi.service.impl;

import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.dao.MerchantwithdrawDao;
import com.youi.entity.Merchantwithdraw;
import com.youi.entity.Merchantwithdrawdetail;
import com.youi.entity.Sysuser;
import com.youi.entity.Userorder;
import com.youi.entity.Userorderexcel;
import com.youi.manage.HttpSessionManage;
import com.youi.service.MerchantwithdrawService;
import com.youi.service.MerchantwithdrawdetailService;
import com.youi.service.SysuserService;
import com.youi.service.UserorderService;
import com.youi.service.UserorderexcelService;
import com.youi.third.ali.oss.OSSUtil;
import com.youi.util.DateUtil;
import com.youi.util.FileUploadUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.SmsUtil;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MerchantwithdrawServiceImpl extends BaseServiceImpl<Merchantwithdraw> implements MerchantwithdrawService {

    private MerchantwithdrawDao merchantwithdrawDao;
    @Autowired
    private SysuserService sysuserService;
    @Autowired
    private MerchantwithdrawdetailService merchantwithdrawdetailService;
    @Autowired
    private UserorderService userorderService;
    @Autowired
    private UserorderexcelService userorderexcelService;

    @Autowired
    public void setfaultRecordDao(MerchantwithdrawDao merchantwithdrawDao) {
        this.merchantwithdrawDao = merchantwithdrawDao;
        super.setBaseDAO(merchantwithdrawDao);
    }

    @Override
    public void getMerchantwithdrawMsg(List<Merchantwithdraw> merchantwithdrawList) {
        if (merchantwithdrawList != null && merchantwithdrawList.size() > 0) {
            for (Merchantwithdraw merchantwithdraw : merchantwithdrawList) {
                getMerchantwithdrawMsg(merchantwithdraw);
            }
        }
    }

    @Override
    public void getMerchantwithdrawMsg(Merchantwithdraw merchantwithdraw) {
        if (merchantwithdraw != null) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put(Common.ID, merchantwithdraw.getCreatedId());
            Sysuser creator = sysuserService.getByParam(params);
            if (creator != null) {
                merchantwithdraw.setCreateName(creator.getName());
            }
            params = new HashMap<String, Object>();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put(Common.ID, merchantwithdraw.getApplyUserId());
            Sysuser applyUser = sysuserService.getByParam(params);
            if (applyUser != null) {
                merchantwithdraw.setApplyUserName(applyUser.getName());
            }
            params = new HashMap<String, Object>();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put("merchantwithdrawId", merchantwithdraw.getId());
            List<Merchantwithdrawdetail> merchantwithdrawdetailList = merchantwithdrawdetailService.getByParams(params);
            if (merchantwithdrawdetailList != null && merchantwithdrawdetailList.size() > 0) {
                merchantwithdraw.setMerchantwithdrawdetailList(merchantwithdrawdetailList);
            }
        }
    }

    @Override
    public void platformToExcelMerchantwithdraw(HttpServletRequest request,
                                                List<Merchantwithdraw> merchantwithdrawList) {
        // TODO Auto-generated method stub
        try {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
            String fileName = "merchantwithdraw" + new Date().getTime() + "" + SmsUtil.getRandom(3) + ".xls";//文件名
            String fileUrl = FileUploadUtil.getUploadUrl(request, "filedownload" + File.separator + fileName);//生成路径
            WritableWorkbook workbook = Workbook.createWorkbook(new File(fileUrl));
            WritableSheet sheet1 = workbook.createSheet("Sheet1", 0);
            WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 10);
            WritableCellFormat format = new WritableCellFormat();
            format.setAlignment(Alignment.CENTRE);
            format.setVerticalAlignment(VerticalAlignment.CENTRE);
            Label label = new Label(0, 0, "提现单号", format);
            sheet1.addCell(label);
            label = new Label(1, 0, "期号", format);
            sheet1.addCell(label);
            label = new Label(2, 0, "供应商名称", format);
            sheet1.addCell(label);
            label = new Label(3, 0, "订单总金额", format);
            sheet1.addCell(label);
            label = new Label(4, 0, "订单总数", format);
            sheet1.addCell(label);
            label = new Label(5, 0, "平台分润总额", format);
            sheet1.addCell(label);
            label = new Label(6, 0, "供应商分润总额", format);
            sheet1.addCell(label);
            label = new Label(7, 0, "分润比例", format);
            sheet1.addCell(label);
            label = new Label(8, 0, "创建时间", format);
            sheet1.addCell(label);
            label = new Label(9, 0, "提现方式", format);
            sheet1.addCell(label);
            label = new Label(10, 0, "审核状态", format);
            sheet1.addCell(label);
            label = new Label(11, 0, "创建人", format);
            sheet1.addCell(label);
            label = new Label(12, 0, "审核人", format);
            sheet1.addCell(label);
            label = new Label(13, 0, "供应商审核时间", format);
            sheet1.addCell(label);
            label = new Label(14, 0, "供应商审核状态", format);
            sheet1.addCell(label);
            label = new Label(15, 0, "审核时间", format);
            sheet1.addCell(label);
            label = new Label(16, 0, "审核意见", format);
            sheet1.addCell(label);
            Merchantwithdraw merchantwithdraw = null;
            for (int i = 0, j = 1; i < merchantwithdrawList.size(); i++, j++) {
                merchantwithdraw = merchantwithdrawList.get(i);
                ObjectUtil.ToChangeNullToEmpty(merchantwithdraw);
                label = new Label(0, j, merchantwithdraw.getTwithdrawNo(), format);
                sheet1.addCell(label);
                label = new Label(1, j, merchantwithdraw.getDateNo(), format);
                sheet1.addCell(label);
                label = new Label(2, j, merchantwithdraw.getMerchantName(), format);
                sheet1.addCell(label);
                label = new Label(3, j, String.valueOf(merchantwithdraw.getOrderAmount()), format);
                sheet1.addCell(label);
                label = new Label(4, j, String.valueOf(merchantwithdraw.getOrderCount()), format);
                sheet1.addCell(label);
                label = new Label(5, j, String.valueOf(merchantwithdraw.getPlatformAmount()), format);
                sheet1.addCell(label);
                label = new Label(6, j, String.valueOf(merchantwithdraw.getMerchantAmount()), format);
                sheet1.addCell(label);
                label = new Label(7, j, String.valueOf(merchantwithdraw.getProfitRatio()), format);
                sheet1.addCell(label);
                label = new Label(8, j, DateUtil.simpdfyMdHms.format(merchantwithdraw.getGmtCreated()), format);
                sheet1.addCell(label);
                label = new Label(9, j, "易宝代付", format);
                sheet1.addCell(label);
                label = new Label(10, j, ObjectUtil.getApplyStatus(merchantwithdraw.getStatus()), format);
                sheet1.addCell(label);
                label = new Label(11, j, merchantwithdraw.getCreateName(), format);
                sheet1.addCell(label);
                label = new Label(12, j, merchantwithdraw.getApplyUserName(), format);
                sheet1.addCell(label);
                if (merchantwithdraw.getGmtMerchantApply() != null) {
                    label = new Label(13, j, DateUtil.simpdfyMdHms.format(merchantwithdraw.getGmtMerchantApply()), format);
                    sheet1.addCell(label);
                }
                label = new Label(14, j, ObjectUtil.getMerchantApplyStatus(merchantwithdraw.getMerchantStatus()), format);
                sheet1.addCell(label);
                if (merchantwithdraw.getGmtApply() != null) {
                    label = new Label(15, j, DateUtil.simpdfyMdHms.format(merchantwithdraw.getGmtApply()), format);
                    sheet1.addCell(label);
                }
                label = new Label(16, j, merchantwithdraw.getPlatformIdea(), format);
                sheet1.addCell(label);
            }
            workbook.write();
            workbook.close();
            InputStream inStream = new FileInputStream(fileUrl);
            byte[] data = ObjectUtil.readInputStream(inStream);
            String dowmupload = OSSUtil.upload(data, ".xls");
            if (dowmupload != null && dowmupload.length() > 0) {
                userorderexcelService.saveOrUpdate(new Userorderexcel(sysuser.getId(), 2, dowmupload));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void merchantToExcelMerchantwithdraw(HttpServletRequest request,
                                                List<Merchantwithdraw> merchantwithdrawList) {
        // TODO Auto-generated method stub
        try {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
            String fileName = "merchantwithdraw" + new Date().getTime() + "" + SmsUtil.getRandom(3) + ".xls";//文件名
            String fileUrl = FileUploadUtil.getUploadUrl(request, "filedownload" + File.separator + fileName);//生成路径
            WritableWorkbook workbook = Workbook.createWorkbook(new File(fileUrl));
            WritableSheet sheet1 = workbook.createSheet("Sheet1", 0);
            WritableFont font = new WritableFont(WritableFont.createFont("微软雅黑"), 10);
            WritableCellFormat format = new WritableCellFormat();
            format.setAlignment(Alignment.CENTRE);
            format.setVerticalAlignment(VerticalAlignment.CENTRE);
            Label label = new Label(0, 0, "提现单号", format);
            sheet1.addCell(label);
            label = new Label(1, 0, "期号", format);
            sheet1.addCell(label);
            label = new Label(2, 0, "供应商名称", format);
            sheet1.addCell(label);
            label = new Label(3, 0, "供应商编码", format);
            sheet1.addCell(label);
            label = new Label(4, 0, "订单总金额", format);
            sheet1.addCell(label);
            label = new Label(5, 0, "订单总数", format);
            sheet1.addCell(label);
            label = new Label(6, 0, "订单分润", format);
            sheet1.addCell(label);
            label = new Label(7, 0, "分润比例", format);
            sheet1.addCell(label);
            label = new Label(8, 0, "提现方式", format);
            sheet1.addCell(label);
            label = new Label(9, 0, "审核状态", format);
            sheet1.addCell(label);
            label = new Label(10, 0, "审核时间", format);
            sheet1.addCell(label);
            label = new Label(11, 0, "审核意见", format);
            sheet1.addCell(label);
            Merchantwithdraw merchantwithdraw = null;
            for (int i = 0, j = 1; i < merchantwithdrawList.size(); i++, j++) {
                merchantwithdraw = merchantwithdrawList.get(i);
                ObjectUtil.ToChangeNullToEmpty(merchantwithdraw);
                label = new Label(0, j, merchantwithdraw.getTwithdrawNo(), format);
                sheet1.addCell(label);
                label = new Label(1, j, merchantwithdraw.getDateNo(), format);
                sheet1.addCell(label);
                label = new Label(2, j, merchantwithdraw.getMerchantName(), format);
                sheet1.addCell(label);
                label = new Label(3, j, merchantwithdraw.getMerchantCode(), format);
                sheet1.addCell(label);
                label = new Label(4, j, String.valueOf(merchantwithdraw.getOrderAmount()), format);
                sheet1.addCell(label);
                label = new Label(5, j, String.valueOf(merchantwithdraw.getOrderCount()), format);
                sheet1.addCell(label);
                label = new Label(6, j, String.valueOf(merchantwithdraw.getMerchantAmount()), format);
                sheet1.addCell(label);
                label = new Label(7, j, String.valueOf(merchantwithdraw.getProfitRatio()), format);
                sheet1.addCell(label);
                label = new Label(8, j, "易宝代付", format);
                sheet1.addCell(label);
                label = new Label(9, j, ObjectUtil.getApplyStatus(merchantwithdraw.getStatus()), format);
                sheet1.addCell(label);
                String gmtApply = null;
                if (merchantwithdraw.getGmtApply() != null) {
                    gmtApply = DateUtil.simpdfyMdHms.format(merchantwithdraw.getGmtApply());
                }
                label = new Label(10, j, gmtApply, format);
                sheet1.addCell(label);
                label = new Label(11, j, merchantwithdraw.getMerchantIdea(), format);
                sheet1.addCell(label);
            }
            workbook.write();
            workbook.close();
            InputStream inStream = new FileInputStream(fileUrl);
            byte[] data = ObjectUtil.readInputStream(inStream);
            String dowmupload = OSSUtil.upload(data, ".xls");
            if (dowmupload != null && dowmupload.length() > 0) {
                userorderexcelService.saveOrUpdate(new Userorderexcel(sysuser.getId(), 2, dowmupload));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RowsExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public Integer updateUserordeMerchantWithdraw(Merchantwithdraw merchantwithdraw, Integer status, Integer type) {
        // TODO Auto-generated method stub
        List<String> orderNoList = new ArrayList<String>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put("merchantwithdrawId", merchantwithdraw.getId());
        List<Merchantwithdrawdetail> merchantwithdrawdetailList = merchantwithdrawdetailService.getByParams(params);
        if (merchantwithdrawdetailList == null || merchantwithdrawdetailList.size() == 0) {
            return 0;
        }
        for (Merchantwithdrawdetail merchantwithdrawdetail : merchantwithdrawdetailList) {
            orderNoList.add(merchantwithdrawdetail.getOrderNo());
        }
        ObjectUtil.removeDuplicate(orderNoList);
        params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put("orderNo", orderNoList);
        List<Userorder> userorderList = userorderService.getByParams(params);
        if (userorderList == null || userorderList.size() == 0) {
            return 0;
        }
        if (status == -1) {
            for (Userorder userorder : userorderList) {
                userorder.setMerchantStatus(4);
                userorderService.saveOrUpdate(userorder);
            }
            for (Merchantwithdrawdetail merchantwithdrawdetail : merchantwithdrawdetailList) {
                merchantwithdrawdetail.setMerchantStatus(4);
            }
            merchantwithdrawdetailService.saveOrUpdateAll(merchantwithdrawdetailList);
        }
        return 1;
    }

    @Override
    public List<Map<String, Object>> listMerchantWithdrawData(Map<String, Object> param) {
        List<Map<String, Object>> list = merchantwithdrawDao.listMerchantWithdrawData(param);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        list.stream().forEach(withdraw -> {
            withdraw.put("withdrawType", "易宝代付");
            withdraw.put("statusTxt", ObjectUtil.getPlatformApplyStatus((Integer) withdraw.get("status")));
            withdraw.put("merchantStatusTxt", ObjectUtil.getPlatformApplyStatus((Integer) withdraw.get("status")));
            withdraw.put("platformStatusTxt", ObjectUtil.getPlatformApplyStatus((Integer) withdraw.get("status")));
            if (withdraw.get("gmtCreated") != null) {
                try {
                    withdraw.put("gmtCreated", DateUtil.simpdfyMdHms.format(DateUtil.simpdfyMdHms.parse(String.valueOf(withdraw.get("gmtCreated")))));
                } catch (Exception e) {
                }
            }
            if (withdraw.get("gmtMerchantApply") != null) {
                try {
                    withdraw.put("gmtMerchantApply", DateUtil.simpdfyMdHms.format(DateUtil.simpdfyMdHms.parse(String.valueOf(withdraw.get("gmtMerchantApply")))));
                } catch (Exception e) {
                }
            }
            if (withdraw.get("gmtApply") != null) {
                try {
                    withdraw.put("gmtApply", DateUtil.simpdfyMdHms.format(DateUtil.simpdfyMdHms.parse(String.valueOf(withdraw.get("gmtApply")))));
                } catch (Exception e) {
                }
            }
        });
        return list;
    }
}